﻿using ADODB;
using fuzhu;
using LH.Model.PU;
using LH.Model.ST;
using SqlSuarEntity;
using SqlSugar;
using System.Data;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.XXXEntities;
using ZDEntity; 

namespace Yonyou.U8.BO
{

    public class TransVouchAppVM : ST_TransVouchApp
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public bool bWMS = false;
        public string cDatabase = "";


        public TransVouchAppVM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }



        public RetModel2 AddVerify()
        {
            try
            {
                string idcheck = "";
                if (Exists(ref idcheck))
                {
                    return DBService.ReErrObject($"当前单据号{this.head.cTVCode}已存在");
                } 
                foreach (Body body in bodies)
                {
                    body.editprop = "A";
                }

                string cRe = GetAddInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }

                //调拨单，额外增加其他出入库单的处理
                if (!TransVouchAppDALCO.AddVerify(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //审核失败后，检查是否有采购入库单生成，如果有，则删除
                    string cerr2 = "";
                    if (!string.IsNullOrEmpty(id))
                    {
                        TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "delete", out cerr2);
                    }

                    return DBService.ReErrObject("新增失败：" + err);
                }
                else
                {

                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                        DateTime dDate = DbHelper.GetDbDate(head.dTVDate);
                        int iid = DbHelper.GetDbInt(id);
                       
                        db.Updateable<ST_AppTransVouch>()
                 .SetColumns(u => new ST_AppTransVouch()
                 {
                     dVerifyDate = dDate,
                     cVerifyPerson = head.cMaker
                 })
                 .Where(u => u.ID == iid)
                 .ExecuteCommand();

                        //更新调拨申请单的 数量
                        db.Updateable<ST_AppTransVouchs>()
               .SetColumns(u => new ST_AppTransVouchs()
               {
                   iTvChkQuantity =u.iTVQuantity,
                   iTVChkNum = u.iTVNum
               })
               .Where(u => u.ID == iid)
               .ExecuteCommand();

                        //    //不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                        //    if (!bWMS)
                        //    {

                        //        if (ccode != head.cTVCode && head.cTVCode != WMSPara.rdTVCode)
                        //        {
                        //            //单据编码选项判断
                        //            string sqlrep = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='0304'");
                        //            int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sqlrep));
                        //            if (iRepeat == 1)
                        //            {
                        //                string cerr2 = "";
                        //                TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "unverify,delete", out cerr2);
                        //                return DBService.ReOKObject("单据已生成，重复");
                        //            }
                        //        }
                        //    }
                        //    else
                        //    {
                        //        //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                        //        string cParentid = head.cDefine10;
                        //        if (!string.IsNullOrEmpty(cParentid))
                        //        {
                        //            //检查cParentid 是否存在
                        //            string sqlcx = string.Format(@"select count(*) sl from transvouch a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                        //            int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                        //            if (icntUniq > 0)
                        //            {
                        //                TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "unverify,delete", out _);
                        //                return DBService.ReOKObject("之前单据已生成，重复");
                        //            }
                        //        } 
                        //    }

                        //   string sql = string.Format("select id from rdrecord09 where cbustype='调拨出库' and  cbuscode = '{0}'", ccode);
                        //    string iid9 = DbHelper.GetDbString(db.Ado.GetScalar(sql));
                        //    string cerr = "";
                        //    if (!Rdrecord09DALCO.VerifyRdrecord09(iid9, xmlConfig, "verify", out cerr))
                        //    {
                        //        //删除掉调拨单
                        //        string cerr2 = "";
                        //        TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "unverify,delete", out cerr2);
                        //        throw new Exception(cerr);
                        //    };

                        //    sql = string.Format("select id from rdrecord08 where cbustype='调拨入库' and  cbuscode = '{0}'", ccode);
                        //    string iid8 = DbHelper.GetDbString(db.Ado.GetScalar(sql));
                        //    if (!Rdrecord08DALCO.VerifyRdrecord08(iid8, xmlConfig, "verify", out cerr))
                        //    {
                        //        // 删除掉调拨单
                        //        string cerr2 = "";
                        //        TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "unverify,delete", out cerr2);
                        //        throw new Exception(cerr);
                        //    }

                    }


                }
                    //生成的id赋值
                    head.ID = id;
                head.cTVCode = ccode;
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }



        public string GetAddInfo()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        string cInvCode = bodies[i].cInvCode;
                      
                         
                        InvProperty invProperty = new InventoryVM().GetInvProperty(bodies[i].cInvCode, bodies[i].dMadeDate, bodies[i].dDisDate);
                        if (invProperty == null)
                        {
                            return string.Format("第{0}行订单物料{1}不存在", (i + 1).ToString(), bodies[i].cInvCode);
                        }
                        //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                        if (invProperty.iGroupType != "0")
                        {
                            //辅助计量单位来源于来源单据，如果没有取库存单位
                            if (string.IsNullOrEmpty(bodies[i].cAssUnit))
                            {
                                bodies[i].cAssUnit = invProperty.cSTComUnitCode;
                            }

                            if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].iinvexchrate)) || DbHelper.GetDbString(bodies[i].iinvexchrate)=="0")
                            {
                                bodies[i].iinvexchrate = invProperty.iChangRate;
                            }
                            if (DbHelper.GetDbdecimal(bodies[i].iinvexchrate)!=0)
                            {
                                bodies[i].iTVNum = (DbHelper.GetDbdecimal(bodies[i].iTVQuantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                            }
                          
                        }

                        ////是否批次管理
                        //if (!invProperty.bInvBatch)
                        //{
                        //    bodies[i].cTVBatch = "";
                        //}
                        //else if (string.IsNullOrEmpty(bodies[i].cTVBatch))
                        //{
                        //    return string.Format("第{0}行订单物料{1}有批次管理，未录入批次", (i + 1).ToString(), cInvCode);
                        //}
                        ////自由项，未处理

                        ////有效期管理,根据生产日期或者失效日期推算 
                        //if (invProperty.bInvQuality)
                        //{
                        //    if (string.IsNullOrEmpty(bodies[i].dMadeDate) && string.IsNullOrEmpty(bodies[i].dDisDate))
                        //    {
                        //        return string.Format("第{0}行物料生产日期或者失效日期未录入", (i + 1).ToString());
                        //    }
                        //    else
                        //    {
                        //        bodies[i].dDisDate = DbHelper.GetDbDate(invProperty.dVDate).ToString("yyyy-MM-dd");
                        //        bodies[i].iMassDate = DbHelper.GetDbString(invProperty.iMassDate);
                        //        bodies[i].cMassUnit = DbHelper.GetDbString(invProperty.cMassUnit);
                        //        bodies[i].dExpirationdate = DbHelper.GetDbDate(invProperty.dExpeireDate).ToString("yyyy-MM-dd"); ;
                        //        bodies[i].iExpiratDateCalcu = DbHelper.GetDbString(invProperty.iexpiratdatecalcu);
                        //    }


                        //}
                        FitemVM fitemVM = new FitemVM();

                        if (fitemVM.GetName(bodies[i].cItem_class, bodies[i].cItemCode, out string citem_cname, out string citemname) == "ok")
                        {
                            bodies[i].cItemCName = citem_cname;
                            bodies[i].cName = citemname;
                        }

                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }





            return "ok";
        }


        /// <summary>
        /// 检查单据号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from ST_AppTransVouch where ctvcode='{0}' ", head.cTVCode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));
                
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }


       

        public RetModel2 UnverifyDelete()
        {
            //审核失败后，检查是否有其他入库单生成，如果有，则删除
            string cerr2 = "";
            string ID = "";
            if (!Exists(ref ID))
            {
                return DBService.ReOKObject("当前单据号已删除");
            }
            if (!TransVouchAppDALCO.Verify(ID, xmlConfig, "unverify,delete", out string err))
            {
                return DBService.ReErrObject("弃审失败：" + err);
            }


            return DBService.ReOKObject("删除完成");

        }


        /// <summary>
        /// 新增实体，根据申请单
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public TransVouchAppVM GetAddEntity(API_TransVouch obj, ref string cErr)
        {

            try
            { 
                ST_TransVouchApp.Head head = new ST_TransVouchApp.Head
                {
                    bWireless = "1",
                    csource = "1",
                    itransflag = "正向",
                    dTVDate = obj.dDate,
                    cIWhCode = obj.cIWhCode,
                    cOWhCode = obj.cOWhCode, 
                    cORdCode = CanShu.RdTV09,
                    cIRdCode = CanShu.RdTV08,
                    cMaker = obj.cMaker,
                //rdHead.cVerifyPerson = scanBarcodes.cUserName;
                cTVCode = obj.cTVCode,
                iPrintCount = "0",  
                cDefine1 = obj.cDefine1,
                  cDefine2 = obj.cDefine2,
                    cDefine3 = obj.cDefine3,
                    cDefine4 = obj.cDefine4,
                    cDefine5 = obj.cDefine5,
                    cDefine6 = obj.cDefine6,
                    cDefine7 = obj.cDefine7,
                    cDefine8 = obj.cDefine8,
                    cDefine9 = obj.cDefine9,
                    cDefine10 = obj.cDefine10,
                    cDefine11 = obj.cDefine11,
                    cDefine12 = obj.cDefine12,
                    cDefine13 = obj.cDefine13,
                    cDefine14 = obj.cDefine14,
                    cDefine15 = obj.cDefine15,
                    cDefine16 = obj.cDefine16,
                };
                //if (obj.cSource == "调拨申请调拨")
                //{
                //    head.cTranRequestCode = obj.cTranRequestCode;   //来源单号 
                //}
                List<LH.Model.ST.ST_TransVouchApp.Body> bodies = new List<LH.Model.ST.ST_TransVouchApp.Body>();

                 
               if (obj.itemList != null && obj.itemList.Count > 0)
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {


                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }

                            i++;
                            ST_TransVouchApp.Body body = new ST_TransVouchApp.Body
                            {

                                cInvCode = item.cInvCode,
                                //cfree1 = item.cFree1,
                                //cfree2 = item.cFree2,
                                //cfree3 = item.cFree3,
                                //cfree4 = item.cFree4,
                                irowno = i.ToString(),
                                iTVQuantity = DbHelper.GetDbString(item.iQuantity),
                                //iTvChkQuantity = DbHelper.GetDbString(item.iQuantity),
                                iTVNum = DbHelper.GetDbString(item.iNum),
                                //iTVChkNum = DbHelper.GetDbString(item.iNum),
                                cTVBatch = item.cBatch,
                                 coutposcode= item.cOPosCode,
                                 cinposcode = item.cIPosCode,
                               
                                cbMemo = item.cBMemo,
                                cItemCode = item.cItemCode,
                                cItemCName = item.cItem_Name,
                                cItem_class = item.cItem_Class,
                                //33自定义项作为mes行id
                                cDefine31 = item.cRowId,

                                //从22 写到37
                                cDefine22 = item.cDefine22,
                                cDefine23 = item.cDefine23,
                                cDefine24 = item.cDefine24,
                                cDefine25 = item.cDefine25,
                                cDefine26 = item.cDefine26,
                                cDefine27 = item.cDefine27,
                                cDefine28 = item.cDefine28,
                                cDefine29 = item.cDefine29,
                                cDefine30 = item.cDefine30, 
                                cDefine32 = item.cDefine32,
                                cDefine33= item.cDefine33,
                                cDefine34 = item.cDefine34,
                                cDefine35 = item.cDefine35,
                                cDefine36 = item.cDefine36,
                                cDefine37 = item.cDefine37

                            }; 

                            bodies.Add(body);
                        }
                    }
                }



                TransVouchAppVM model = new TransVouchAppVM(head, bodies);
                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }

        }

        /// <summary>
        /// 传入json转换成 vm
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public TransVouchAppVM GetCodeEntity(API_TransVouch obj, ref string cErr)
        {

            try
            {

                ST_TransVouchApp.Head head = new ST_TransVouchApp.Head();
                head.cTVCode = obj.cTVCode;
                List<ST_TransVouchApp.Body> bodies = new List<ST_TransVouchApp.Body>();

                TransVouchAppVM model = new TransVouchAppVM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }
             
        }
        
         


    }
}
